<template>
	<view class="main-layout">
		<view class="content">
			<slot />
		</view>

		<CustomTabBar v-if="showTabBar" v-model="tabIndex" :items="menuItems" @menuClick="onMenuClick" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue'
	import CustomTabBar from '@/components/CustomTabBar.vue'
	import {
		tabbarConfig
	} from '@/utils/tabbar'

	const tabIndex = ref(0)
	const showTabBar = ref(false)
	const menuItems = tabbarConfig.items

	const getCurrentPath = () => {
		const pages = getCurrentPages()
		if (!pages.length) return '/'
		const page = pages[pages.length - 1]
		return '/' + page.route
	}

	const updateTabBar = () => {
		if (!menuItems || !menuItems.length) return

		const currentPath = getCurrentPath()
		const normalizedPath = currentPath === '/' ? '/pages/index/index' : currentPath
		const tabPaths = menuItems.map(item => item?.url || '')

		const matchedIndex = tabPaths.findIndex(p => normalizedPath.includes(p))
		tabIndex.value = matchedIndex !== -1 ? matchedIndex : 0
		showTabBar.value = matchedIndex !== -1

		// console.log('📍 当前路径:', normalizedPath, '显示tabBar:', showTabBar.value)
	}

	onMounted(() => {
		updateTabBar()
	})

	const onMenuClick = (index) => {
		const item = menuItems[index]
		if (!item || !item.url) return

		// 🔹 判断是否点击发布页
		if (item.text === '发布') {
			const token = uni.getStorageSync('token')
			if (!token) {
				uni.reLaunch({
					url: '/pages/login/index'
				})
				return
			}
		}

		const currentPath = getCurrentPath()
		if (item.url === currentPath) return

		if (item.url === '/pages/index/index') {
			uni.reLaunch({
				url: item.url
			})
		} else {
			uni.redirectTo({
				url: item.url
			})
		}
	}
</script>

<style scoped>
	.main-layout {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.content {
		flex: 1;
		padding-bottom: 100rpx;
		/* 预留菜单高度 */
	}
</style>